package com.tripshare.logic.service;

import com.tripshare.sdk.weixin.api.IMsgProcessor;
import com.tripshare.sdk.weixin.api.util.JsonUtil;
import com.tripshare.sdk.weixin.format.WeixinBaseMsg;
import com.tripshare.sdk.weixin.format.WeixinBaseReplyMsg;
import com.tripshare.sdk.weixin.format.receive.*;
import com.tripshare.sdk.weixin.format.reply.WeixinTextReplyMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class IMsgProcessorImpl implements IMsgProcessor {

    @Override
    public WeixinBaseReplyMsg processTextMsg(WeixinTextMsg textMsg) {
        log.info("processTextMsg={}", JsonUtil.gson.toJson(textMsg));
        String content = textMsg.getContent();
        return createTextReplyMsg(textMsg, "欢迎关注公众号");
    }

    @Override
    public WeixinBaseReplyMsg processVoiceMsg(WeixinVoiceMsg voiceMsg) {
        log.info("processVoiceMsg={}", JsonUtil.gson.toJson(voiceMsg));
        return createTextReplyMsg(voiceMsg, "收到语音消息");
    }

    @Override
    public WeixinBaseReplyMsg processLocationMsg(WeixinLocationMsg locationMsg) {
        log.info("processLocationMsg={}", JsonUtil.gson.toJson(locationMsg));
        String locationContent = String.format("位置: %s\nX: %s, Y: %s", locationMsg.getLabel(), locationMsg.getLocation_X(), locationMsg.getLocation_Y());
        return createTextReplyMsg(locationMsg, locationContent);
    }

    @Override
    public WeixinBaseReplyMsg processScanCodeMsg(WeixinScanCodeMsg scanCodeMsg) {
        log.info("processScanCodeMsg={}", JsonUtil.gson.toJson(scanCodeMsg));
        String scanContent = String.format("ScanType: %s\nScanResult: %s", scanCodeMsg.getScanCodeInfo().getScanType(), scanCodeMsg.getScanCodeInfo().getScanResult());
        return createTextReplyMsg(scanCodeMsg, scanContent);
    }

    @Override
    public WeixinBaseReplyMsg processClickMsg(WeixinClickMsg clickMsg) {
        log.info("processClickMsg={}", JsonUtil.gson.toJson(clickMsg));
        if ("financial_key".equals(clickMsg.getEventKey())) {
            String clickContent = String.format("沪深300:%s\n银行组合：%s", 5000, 5000);
            return createTextReplyMsg(clickMsg, clickContent);
        } else {
            return createTextReplyMsg(clickMsg, clickMsg.getEventKey());
        }
    }

    private WeixinTextReplyMsg createTextReplyMsg(WeixinBaseMsg textMsg, String content) {
        WeixinTextReplyMsg replyMsg = new WeixinTextReplyMsg();
        replyMsg.setContent(content);
        replyMsg.setToUserName(textMsg.getFromUserName());
        replyMsg.setFromUserName(textMsg.getToUserName());
        replyMsg.setCreateTime(textMsg.getCreateTime());
        replyMsg.setMsgType("text");
        return replyMsg;
    }

}
